<template>
  <div class="echarts" :style="'width:' + width +'; height:'+ height+';'"></div>
</template>

<script>
  import echarts from 'echarts/lib/echarts'
  import 'zrender/lib/svg/svg';

  const INIT_TRIGGERS = ['theme', 'initOptions', 'autoresize']
  const REWATCH_TRIGGERS = ['manualUpdate', 'watchShallow']

  export default {
	name: "swak-chart",
	data() {
	  return {}
	},
	props: {
	  options: Object,
	  theme: [String, Object],
	  initOptions: Object,
	  watchShallow: Boolean,
	  manualUpdate: Boolean,
	  autoresize: Boolean,
	  width: {
		type: String,
		default: '100%'
	  },
	  height: {
		type: String,
		default: '400px'
	  },
	},
	created() {
	  INIT_TRIGGERS.forEach(prop => {
		this.$watch(prop, () => {
		  this.refresh()
		}, {deep: true})
	  })
	  REWATCH_TRIGGERS.forEach(prop => {
		this.$watch(prop, () => {
		  this.refresh()
		})
	  })
	},
	watch: {
	  options: {
		handler: function () {
		  if (this.options) {
			this.refreshData();
		  }
		},
		deep: true
	  },
	  '$store.getters.env.screenWidth': function () {
		if (this.chart) {
		  this.refresh()
		}
	  }
	},
	mounted() {
	  if (this.options) {
		this.init()
	  }
	},
	beforeDestroy() {
	  if (!this.chart) {
		return
	  }
	  this.destroy()
	},
	methods: {
	  init() {
		if (this.chart) {
		  return
		}
		let chart = echarts.init(this.$el, this.theme, this.initOptions)
		chart.setOption(this.manualOptions || this.options || {}, true)
		this.chart = chart
	  },
	  dispose() {
		this.delegateMethod('dispose')
	  },
	  delegateMethod(name, ...args) {
		if (!this.chart) {
		  this.init()
		}
		return this.chart[name](...args)
	  },
	  destroy() {
		this.dispose()
		this.chart = null
	  },
	  refreshData() {
		if (this.chart) {
		  this.chart.setOption(this.manualOptions || this.options || {}, true)
		}
	  },
	  refresh() {
		if (this.chart) {
		  this.destroy()
		  this.init()
		}
	  }
	},
  }
</script>

<style scoped>

</style>